# -*- coding: utf-8 -*-
#
# Copyright (c) 2012, Rafael Pivato
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Rafael Pivato nor the names of its contributors
#       may be used to endorse or promote products derived from this
#       software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL RAFAEL PIVATO BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import re
from bcoma import BcomaFormatError
from bcoma import create_api_uri
from bcoma import download_json
from bcoma import download_content


class Item(object):
    """Represents an existing item from the Blizzard Community Site."""

    def __init__(self, data=None):
        """Initializes a new instance of a item object."""
        if data is None:
            self.id = 0
            self.description = ''
            self.name = ''
            self.quality = 0
            self.icon = ''
        else:
            try:
                self.id = data['id']
                self.description = data['description']
                self.name = data['name']
                self.quality = data['quality']
                self.icon = data['icon']
            except KeyError as missing_key:
                detail = 'Missing Item JSON key %s.' % (missing_key)
                raise BcomaFormatError('unknown', missing_key, detail)

    @classmethod
    def fetch(cls, item):
        """Fetches profile information for the given item."""
        path = 'item/%d' % (int(item))
        uri = create_api_uri(path)
        data = download_json(uri)
        if 'status' in data and data['status'] == 'nok':
            return None
        else:
            try:
                obj = cls(data=data)
            except BcomaFormatError as format_error:
                format_error.uri = uri
                raise format_error
            else:
                return obj


class Spell(object):
    """Represents an existing spell.

    As there is no API for gathering spells from the Blizzard Community Site,
    we will be using Wowhead Power interface.

    """

    def __init__(self):
        """Initializes a new instance of a spell object."""
        self.id = 0
        self.name = ''
        self.icon = ''

    @classmethod
    def fetch(cls, spell):
        """Fetches profile information for the given item."""
        uri = 'http://pt.wowhead.com/spell=%d&power' % (int(spell))
        content = download_content(uri)
        name_re = r"name_ptbr: '(.+)',"
        not_found_re = r"\$WowheadPower.registerSpell\(\d+, \d+, {}\);"
        if re.match(not_found_re, content):
            return None
        name_match = re.search(name_re, content)
        if name_match:
            name = name_match.group(1)
        else:
            detail = 'Could not find name in Wowhead spell query response.'
            raise BcomaFormatError(uri, detail=detail)
        icon_re = r"icon: '(.+)',"
        icon_match = re.search(icon_re, content)
        if icon_match:
            icon = icon_match.group(1)
        else:
            detail = 'Could not find uri in Wowhead spell query response.'
            raise BcomaFormatError(uri, detail=detail)
        obj = Spell()
        obj.id = int(spell)
        obj.name = name
        obj.icon = icon
        return obj
